import { createGetAPI } from './fetch';

interface IBanner {
  key: string;
}
interface IBannerItem {
  id: string;
  linkType: string;
  orderIndex: number;
  param: string;
  path: string;
  playImageId: string;
  url: string;
  version: number;
}
export default class Banner {
  private $banner;
  private $box;
  private $loading
  constructor(ele, data: IBanner) {
    this.$banner = $(ele);
    this.$box = $('.banner-inner', this.$banner);
    this.$loading = $('.banner-loading', this.$banner);

    this.loadFromServer();
  }

  loadFromServer() {
    const api = createGetAPI(`bus/home/playImage.htm`, { code: 'HomePlay1' });
    const result = api();
    result.then((result) => {
      this.render(result.body);
    }).catch((error) => {
      console.log(error)
      this.error(this.loadFromServer);
    });
  }
  render(items: IBannerItem[]) {
    this.$loading.hide();
    const html = [];
    const tag = [];
    const minHeight = this.$banner.hasClass('banner-20 ') ? 200 : 300;
    const width = this.$banner.width();
    const height = this.$banner.height();
    if (items) {
      html.push('<ul class="j_slideLists">');
      tag.push('<div class="banner-tag"><ul class="j_slideTags">');
      items.map((item, index) => {
        const src = this.fixPath(item.path, width, height, minHeight);
        html.push(`<li><a href="#"><img src="${src}" alt="${src}" /></a></li>`);
        tag.push(`<li class="${index === 0 ? 'current' : ''}" >< /li>`);
      })
      html.push('</ul>');
      tag.push('</ul></div>');
    }
    this.$box.empty().append(html.join('')).append(tag.join(''));
    this.$banner.slide({ trigger: "click", effect: "fade", auto: true, hoverDelay: 150 });
  }
  fixPath(src, width, height, minHeight) {
    if (height > minHeight) {
      return src;
    } else {
      return `${src}?imageView2/5/w/${width * 2}/h/${height * 2}`;
    }
  }
  loading(text = '加载中...') {
    this.$loading.text(text).show();
  }
  error(callback) {
    this.$loading.text('加载失败，点击重试！').show();
    this.$banner.on('click', () => {
      this.loading();
      callback();
      this.$banner.off('click');
    });
  }
}